# Create your views here.
from django.shortcuts import render_to_response
from google.appengine.api import users
from django import http
#from django.core.paginator import Paginator, InvalidPage
from google.appengine.ext import db
from django.conf import settings

import os
import logging
import datetime
import urllib
import base64
from google.appengine.api import urlfetch

from models import time_details

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}    
  logging.info('before assiging')
  logging.info(params)    
  if user:    
    params['user'] = user
    params['site_name'] = settings.SITE_NAME
    params['sign_out'] = users.CreateLogoutURL('/')
    params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)
    params['site_name'] = settings.SITE_NAME
  if not template.endswith('.html'):
    template += '.html'  
  logging.info(params)
  return render_to_response(template, params)


def index(request, page_num = 1):
  """Request / -- show the last entries for the user."""
  user = users.get_current_user()
  info_dict={}
  template = 'index'
  if user:
    query = db.GqlQuery('select * from time_details where user=:1' , user)
    info_dict = dict(entries = query.fetch(1000))
    template = 'list'
    
  logging.info('details of info dict for user:%s is: %s' % (user, info_dict))  
  
  return respond(request, user, template, info_dict)

def about(request):
  user = users.get_current_user()
  template = 'about'
  return respond(request, user, template)